package beans;

import java.io.IOException;

import java.net.UnknownHostException;

import java.text.ParseException;

import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import javax.servlet.http.HttpServletResponse;

import login.Authentication;

import login.RoleFinder;

import oracle.adf.view.rich.component.rich.input.RichInputText;

import utils.JSFUtils;

public class LoginBean {

    private RichInputText password;
    private RichInputText username;

    public LoginBean() {
        super();
    }

   

    public String validationHelper() throws UnknownHostException,
                                            ParseException {
        Authentication inst1 = new Authentication();
        if (getUsername().getValue() == null ||
            getPassword().getValue() == null) {
        //        JSFUtils.addFacesErrorMessage("Please Enter Credentials And Try Again");
            //  MessageUtils.displayErrorMessage("it1", "Error!!!");
        } else if (getUsername().getValue().equals("") ||
                   getPassword().getValue().equals("")) {
        //        JSFUtils.addFacesErrorMessage("Please Enter Credentials And Try Again");
            //  MessageUtils.displayErrorMessage("it1", "Error!!!");

        } else {
            String Username = getUsername().getValue().toString();
            String Password = getPassword().getValue().toString();
            //System.out.println("Username:" + Username + "\nPassword" +
                 //              Password);
            String Role = inst1.authenticateLogin(Username, Password);
            // //System.out.println("\nrole is:"+Role);
            if (Role == null) {
              JSFUtils.addFacesErrorMessage("Invalid Credentials, Please Try Again");
                password.setValue(null);
               // return null;
            } else if (Role.equals("inActive")) {
              JSFUtils.addFacesErrorMessage("You Are Not Authorised To Use This Portal");
                username.setValue(null);
                password.setValue(null);
                return null;
            } else {
                
        //                mirrorDataService=new MirrorDataService();
        //                MirrorDataServiceSoap mirrorDataServiceSoap=mirrorDataService.getMirrorDataServiceSoap();
        //
        //                ServiceAuthenticationHeader sah=new ServiceAuthenticationHeader();
        //                sah.setUserName("MirrorServiceClient");
        //                sah.setPassword("M!rr0rClient");
        //
        //            AuthenticateX0020TheX0020UserX0020WithX0020AD request=new AuthenticateX0020TheX0020UserX0020WithX0020AD();
        //            request.setUserName(username.getValue().toString());
        //            request.setUserName(password.getValue().toString());
        //                //         request.setEmployeeCode("SP1586");
        //           AuthenticateX0020TheX0020UserX0020WithX0020ADResponse response1=mirrorDataServiceSoap.authenticateADLogin(request,sah);
        //           usr=response1.getAuthenticateX0020TheX0020UserX0020WithX0020ADResult();
        //           usr.getSessionKey();
        //
        //
                
                username.setValue(null);
                password.setValue(null);

                try {


                    
                    FacesContext fctxt = FacesContext.getCurrentInstance();
                    HttpServletResponse response =
                        (HttpServletResponse)fctxt.getExternalContext().getResponse();
                   
                    if(JSFUtils.getFromSession("savedUrl")!=null){
                        String url=JSFUtils.getFromSession("savedUrl").toString();
                        
                    
                        Map sessionState = fctxt.getExternalContext().getSessionMap();
                        sessionState.remove("savedUrl");
                        
                  //      response.sendRedirect(url);
                        fctxt.responseComplete();
                    }
                
                    else{  
                        
                        UserSession session1 =(UserSession)JSFUtils.resolveExpression("#{UserSession}");
                    
                       
                        
                        
                    response.sendRedirect("../faces/Home.jspx");
                    fctxt.responseComplete();
                    }
                    

                } catch (Exception e) {
                    throw new RuntimeException("CustomException during session invalidate. Home.jspx not found");
                }


            }
        }

        return null;
    }
    
    public String processLogout() {
        RoleFinder invalidateRole = new RoleFinder();
        invalidateRole.logoutHelper();
        ExternalContext extc =
            FacesContext.getCurrentInstance().getExternalContext();
        HttpServletResponse resp = (HttpServletResponse)extc.getResponse();
        try {
            resp.sendRedirect("../faces/Login.jspx");
        } catch (IOException e) {
            throw new RuntimeException("Exception during session invalidate. index.html not found");
        }
        FacesContext.getCurrentInstance().responseComplete();
        //System.out.println("\nLog4");
        return "logout";
    }

    public void setPassword(RichInputText password) {
        this.password = password;
    }

    public RichInputText getPassword() {
        return password;
    }

    public void setUsername(RichInputText username) {
        this.username = username;
    }

    public RichInputText getUsername() {
        return username;
    }
}
